package com.zsoft.index;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;

public class IndexCreator {
	// private static AtomicInteger count = new AtomicInteger(0);

	public static void main(String[] args) throws CorruptIndexException, IOException {
		IndexWriter iWriter = getIndexWriter();

		listFile("G:\\快盘\\", iWriter);
		
		iWriter.close();

	}

	public static IndexWriter getIndexWriter() {
		IndexWriter indexWriter = null;
		try {
			File f = new File("H:\\lucene_index\\");
			Directory directory = new SimpleFSDirectory(f);
			IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_36, new StandardAnalyzer(Version.LUCENE_36));
			indexWriter = new IndexWriter(directory, config);
		} catch (IOException e) {
			System.err.println("-----路径不对，索引初始化失败------");
		}
		return indexWriter;
	}

	public static void listFile(String path, IndexWriter indexWriter) throws CorruptIndexException, IOException {

		File f = new File(path);

		File[] file = f.listFiles();
		for (int i = 0; i < file.length; i++) {
			org.apache.lucene.document.Document doc = new org.apache.lucene.document.Document();

			if (file[i].isDirectory()) {
				doc.add(new Field("name", file[i].getName(), Field.Store.YES, Field.Index.NOT_ANALYZED));
				doc.add(new Field("path", file[i].getPath(), Field.Store.YES, Field.Index.NOT_ANALYZED));
				doc.add(new Field("type", "d", Field.Store.YES, Field.Index.NOT_ANALYZED));
				indexWriter.addDocument(doc);
				listFile(file[i].getAbsolutePath(), indexWriter);
				System.out.println("---加入索引目录---" + file[i].getPath());
			} else {
				// 创建索引
				doc.add(new Field("name", file[i].getName(), Field.Store.YES, Field.Index.NOT_ANALYZED));
				doc.add(new Field("path", file[i].getParent(), Field.Store.YES, Field.Index.NOT_ANALYZED));
				doc.add(new Field("type", "f", Field.Store.YES, Field.Index.NOT_ANALYZED));
				indexWriter.addDocument(doc);
				System.out.println("---加入索引文件---" + file[i].getAbsoluteFile());
			}
		}

	}
}
